import React, { useEffect, useMemo, useState } from 'react';
import { Card, List, Tag, Input, Select, Space, Button, Badge, Empty, Row, Col } from 'antd';
import { TeamOutlined, LockOutlined, CheckCircleOutlined, MessageOutlined, SearchOutlined, PlusOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import './ChatList.scss';

interface ChatRoom {
  id: string;
  name: string;
  description?: string;
  type: 'open' | 'approval' | 'closed';
  category: '学习' | '生活' | '兴趣' | '校内通知';
  online: number;
  unread?: number;
}

const { Search } = Input;
const { Option } = Select;

const ChatList: React.FC = () => {
  const navigate = useNavigate();
  const [keyword, setKeyword] = useState('');
  const [typeFilter, setTypeFilter] = useState<'all' | ChatRoom['type']>('all');
  const [categoryFilter, setCategoryFilter] = useState<'all' | ChatRoom['category']>('all');

  const rooms: ChatRoom[] = [
    { id: '1', name: '前端学习交流', description: 'React/TypeScript/工程化', type: 'open', category: '学习', online: 128, unread: 3 },
    { id: '2', name: '算法刷题小组', description: '每日一题，打卡交流', type: 'approval', category: '学习', online: 56, unread: 0 },
    { id: '3', name: '二手好价情报', description: '全网好价，白菜价速报', type: 'open', category: '生活', online: 203, unread: 12 },
    { id: '4', name: '摄影与后期', description: '器材讨论与作品分享', type: 'approval', category: '兴趣', online: 78 },
    { id: '5', name: '校内通知公告', description: '教务处/学生处官方通知', type: 'closed', category: '校内通知', online: 1024 },
  ];

  const filteredRooms = useMemo(() => {
    return rooms.filter((r) => {
      const matchKeyword = keyword ? (r.name.includes(keyword) || (r.description || '').includes(keyword)) : true;
      const matchType = typeFilter === 'all' ? true : r.type === typeFilter;
      const matchCategory = categoryFilter === 'all' ? true : r.category === categoryFilter;
      return matchKeyword && matchType && matchCategory;
    });
  }, [rooms, keyword, typeFilter, categoryFilter]);

  const typeTag = (type: ChatRoom['type']) => {
    switch (type) {
      case 'open':
        return <Tag color="green" icon={<CheckCircleOutlined />}>可直接加入</Tag>;
      case 'approval':
        return <Tag color="gold" icon={<LockOutlined />}>需审核加入</Tag>;
      case 'closed':
        return <Tag color="red" icon={<LockOutlined />}>不可加入</Tag>;
    }
  };

  const handleEnter = (room: ChatRoom) => {
    if (room.type === 'closed') return;
    if (room.type === 'approval') {
      // 模拟审核流程
      // 真实项目应弹出申请表单
      navigate(`/chat/${room.id}?pending=1`);
      return;
    }
    navigate(`/chat/${room.id}`);
  };

  return (
    <div className="chat-list-page">
      <div className="page-header">
        <div className="header-left">
          <h1>聊天室</h1>
          <p>选择你感兴趣的房间开始聊天</p>
        </div>
        <div className="header-right">
          <Button type="primary" icon={<PlusOutlined />}>创建房间</Button>
        </div>
      </div>

      <Card className="filter-card">
        <Space size="middle" wrap>
          <Search
            placeholder="搜索房间名称或简介..."
            allowClear
            onSearch={setKeyword}
            prefix={<SearchOutlined />}
            style={{ width: 300 }}
          />
          <Select value={typeFilter} style={{ width: 140 }} onChange={(v) => setTypeFilter(v)}>
            <Option value="all">全部类型</Option>
            <Option value="open">可直接加入</Option>
            <Option value="approval">需审核加入</Option>
            <Option value="closed">无法加入</Option>
          </Select>
          <Select value={categoryFilter} style={{ width: 140 }} onChange={(v) => setCategoryFilter(v)}>
            <Option value="all">全部分类</Option>
            <Option value="学习">学习</Option>
            <Option value="生活">生活</Option>
            <Option value="兴趣">兴趣</Option>
            <Option value="校内通知">校内通知</Option>
          </Select>
        </Space>
      </Card>

      <Card className="rooms-card">
        {filteredRooms.length === 0 ? (
          <Empty description="暂无符合条件的聊天室" />
        ) : (
          <Row gutter={[16, 16]}>
            {filteredRooms.map((room) => (
              <Col xs={24} sm={12} lg={8} xl={6} key={room.id}>
                <Card
                  hoverable
                  className="room-card"
                  onClick={() => handleEnter(room)}
                >
                  <div className="room-header">
                    <div className="room-icon">
                      <Badge count={room.unread} size="small">
                        <TeamOutlined style={{ fontSize: 40, color: '#1890ff' }} />
                      </Badge>
                    </div>
                  </div>
                  
                  <div className="room-content">
                    <h3 className="room-name">{room.name}</h3>
                    
                    <div className="room-tags">
                      {typeTag(room.type)}
                      <Tag color="purple">{room.category}</Tag>
                    </div>
                    
                    <p className="room-description">{room.description || '暂无简介'}</p>
                    
                    <div className="room-footer">
                      <div className="online-count">
                        <TeamOutlined /> {room.online} 人在线
                      </div>
                      {room.unread && room.unread > 0 && (
                        <div className="unread-count">
                          <MessageOutlined /> {room.unread} 条未读
                        </div>
                      )}
                    </div>
                  </div>
                </Card>
              </Col>
            ))}
          </Row>
        )}
      </Card>
    </div>
  );
};

export default ChatList;
